﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace DataAccessor.Protector
{
    /// <summary>
    /// 配置文件保密算法.
    /// 加密算法来自：http://www.cnblogs.com/zengxiangzhan/archive/2010/01/30/1659687.html
    /// </summary>
    public class DAProtector : IProtector
    {
        private SymmetricAlgorithm cryptographyService;
        private string cryptographyKey;

        public string DecryptConnectionString(string connectionString)
        {
            var ciphertext = Convert.FromBase64String(connectionString);
            var plaintext = Decrypt(ciphertext);
            return Encoding.Default.GetString(plaintext);
        }

        public void DecryptTSQLFile(string encryptedFile, string decryptedFile)
        {
            var buffer = File.ReadAllBytes(encryptedFile);
            var plaintext = Decrypt(buffer);
            File.WriteAllBytes(decryptedFile, plaintext);
        }

        public string EncryptConnectionString(string connectionString)
        {
            var plaintext = Encoding.Default.GetBytes(connectionString);
            var ciphertext = Encrypt(plaintext);
            return Convert.ToBase64String(ciphertext);
        }

        public void EncryptTSQLFile(string sourceFile, string encryptedFile)
        {
            var buffer = File.ReadAllBytes(sourceFile);
            var ciphertext = Encrypt(buffer);
            File.WriteAllBytes(encryptedFile, ciphertext);
        }

        /// <summary>
        /// 加密算法
        /// </summary>
        public DAProtector()
        {
            cryptographyService = new RijndaelManaged();
            cryptographyKey = "pingpang dataaccessor by Will Zhang.contact to:zhangwei923@hotmail.com";
            cryptographyService.Key = GetLegalKey();
            cryptographyService.IV = GetLegalIV();
        }
        /// <summary>    
        /// 获得密钥    
        /// </summary>    
        /// <returns>密钥</returns>    
        private byte[] GetLegalKey()
        {
            string tempKey = cryptographyKey;
            cryptographyService.GenerateKey();
            byte[] cryptographyKeyByteArray = cryptographyService.Key;
            int KeyLength = cryptographyKeyByteArray.Length;
            if (tempKey.Length > KeyLength)
            {
                tempKey = tempKey.Substring(0, KeyLength);
            }
            else if (tempKey.Length < KeyLength)
            {
                tempKey = tempKey.PadRight(KeyLength, ' ');
            }
            return ASCIIEncoding.ASCII.GetBytes(tempKey);
        }

        /// <summary>    
        /// 获得初始向量IV    
        /// </summary>    
        /// <returns>初试向量IV</returns>    
        private byte[] GetLegalIV()
        {
            string iv = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
            cryptographyService.GenerateIV();
            byte[] bytTemp = cryptographyService.IV;
            int IVLength = bytTemp.Length;
            if (iv.Length > IVLength)
            {
                iv = iv.Substring(0, IVLength);
            }
            else if (iv.Length < IVLength)
            {
                iv = iv.PadRight(IVLength, ' ');
            }
            return ASCIIEncoding.ASCII.GetBytes(iv);
        }
        /// <summary>    
        /// 加密  
        /// </summary>
        private byte[] Encrypt(byte[] plaintext)
        {
            var encryptor = cryptographyService.CreateEncryptor();
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    cs.Write(plaintext, 0, plaintext.Length);
                    cs.FlushFinalBlock();
                    return ms.ToArray();
                }
            }
        }
        /// <summary>    
        /// 解密   
        /// </summary>    
        private byte[] Decrypt(byte[] ciphertext)
        {
            using (MemoryStream ms = new MemoryStream(ciphertext, 0, ciphertext.Length))
            {
                ICryptoTransform decryptor = cryptographyService.CreateDecryptor();
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    byte[] buffer = new byte[ciphertext.Length];
                    cs.Read(buffer, 0, (int)ciphertext.Length);
                    return buffer;
                }
            }
        }
    }
}
